﻿#include "itemadd.h"
#include "ui_itemadd.h"

ItemAdd::ItemAdd(QWidget *parent, const QString &table) :
    QDialog(parent),
    _table(table),
    ui(new Ui::ItemAdd)
{
    ui->setupUi(this);

    baseTime=QTime(6,0);
    ui->time->setTime(QTime::currentTime());

    items.insert(TEXT_REMIND,ACTION_REMIND);
    items.insert(TEXT_OPEN,ACTION_OPEN);
    items.insert(TEXT_EXECUTE,ACTION_EXECUTE);

    QStringList list;
    list.append(TEXT_REMIND);
    list.append(TEXT_OPEN);
    list.append(TEXT_EXECUTE);
    ui->action->addItems(list);
    ui->action->setCurrentIndex(-1);
    ui->btn_pick->setEnabled(false);
}

ItemAdd::~ItemAdd()
{
    delete ui;
}

bool ItemAdd::addItem(int week, const QTime &time, const QString &actor,
                      int action, const QString &extra)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (uid,week,time,actor,action,extra) values (?,?,?,?,?,?)").arg(_table));
    query.addBindValue(QUuid::createUuid().toString());
    query.addBindValue(week);
    query.addBindValue(time);
    query.addBindValue(actor);
    query.addBindValue(action);
    query.addBindValue(extra);

    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void ItemAdd::on_btn_submit_clicked()
{
    int week=ui->week->value();
    QTime time=ui->time->time();
    if(time < baseTime)
        return;

    QString actor=ui->actor->text().trimmed();
    if(actor.isEmpty())
        return;

    QString key=ui->action->currentText();
    int action=0;
    if(items.contains(key))
        action=items.value(key);

    if(action == 0)
        return;

    QString extra=ui->extra->text().trimmed();
    if(extra.isEmpty())
        return;

    if(!addItem(week,time,actor,action,extra))
        QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("无法提交数据！"));
    else
        this->accept();
}

void ItemAdd::on_btn_pick_clicked()
{
    QUrl url=QFileDialog::getOpenFileUrl(this);
    if(url.isEmpty())
        return;

    ui->extra->setText(url.toString());
}

void ItemAdd::on_week_valueChanged(int value)
{
    if(value == 0)
        ui->lbl_week->setText(QStringLiteral("每天"));
    else
        ui->lbl_week->setText(QStringLiteral("每周 ") + QString::number(value));
}

void ItemAdd::on_action_currentTextChanged(const QString &text)
{
    if(text == TEXT_OPEN)
        ui->btn_pick->setEnabled(true);
    else
        ui->btn_pick->setEnabled(false);
}
